﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;

namespace Sharp.Platform.WebAPI.Filter
{
    /// <summary>
    /// 试验失败
    /// </summary>
    public class CompressActionFilter : System.Web.Http.Filters.IActionFilter
    {
        public bool AllowMultiple { get; }
        public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            IEnumerable<string> arr;
            HttpResponseMessage response = continuation().Result;

            if (!actionContext.Request.Headers.TryGetValues("Accept-Encoding", out arr))
            {
                return Task.FromResult(response);
            }

            var acceptEncoding = arr.First().ToUpper();
            if (acceptEncoding.Contains("GZIP"))
            { 
                var data = response.Content.ReadAsByteArrayAsync().Result;

                using (MemoryStream stream = new MemoryStream())
                {
                    using (var gZipStream = new GZipStream(stream, CompressionMode.Compress))
                    {
                        gZipStream.Write(data, 0, data.Length);
                        gZipStream.Close();
                    }
                    var yas = stream.ToArray();
                    response.Content = new ByteArrayContent(yas);
                }

            }
            //else if (acceptEncoding.Contains("DEFLATE"))
            //{
            //    response.Headers.Add("Content-encoding", "deflate");
            //    //response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            //}

            return Task.FromResult(response);
        }
    }
}
